

set :stage,:production
set :deploy_to,"/var/www/apps/guike"
set :rvm1_ruby_version,"ruby-2.3.0"
set :rails_env,"production"
set :default_env,{
    rvm_bin_path:"/usr/local/rvm/bin",
    path:"/usr/local/rvm/gems/ruby-2.3.3/bin:/usr/local/rvm/gems/ruby-2.3.3@global/bin:/usr/local/rvm/rubies/ruby-2.3.3/bin:/usr/local/games:/usr/local/rvm/bin:$PATH",
    ruby_version:'ruby-2.3.3',
    "GEM_HOME" => '/usr/local/rvm/gems/ruby-2.3.3',
    "GEM_PATH" => '/usr/local/rvm/gems/ruby-2.3.3',
}


server "120.27.112.196",user:"root", roles: %w{web app db production}
SSHKit::Backend::Netssh.configure do |ssh|
  ssh.connection_timeout = 30
  ssh.ssh_options = {
      user:"root",
      keys: %w(/Users/xuzhaolin/.ssh/id_rsa),
      auth_methods: ['publickey']
  }
end


namespace :deploy do

  namespace :symlink do
    task :link_uploads do
      on "root@120.27.112.196" do
        execute :cp, "-fr","#{release_path}/config/database.production.yml #{release_path}/config/database.yml"
        execute :rm, "-rf","#{release_path}/public/uploads"
        execute :ln, "-sf","/var/www/apps/upload/guike #{release_path}/public/uploads"
      end
    end
  end

  after "deploy:symlink:shared", "deploy:symlink:link_uploads"


  desc "Start unicorn"
  task :start_unicorn do
    on roles(:app) do
      within "#{fetch(:deploy_to)}/current" do
        with RALS_ENV: fetch(:rails_env) do
          execute :magic_encoding
          execute :unicorn_rails,"-c","#{deploy_to}/current/config/unicorn.rb","--env","production","-D"
        end
      end
    end
  end

  desc "Restart unicorn"
  task :restart_unicorn do
    on roles(:app) do
      within "#{fetch(:deploy_to)}/current" do
        with RALS_ENV: fetch(:rails_env) do
          execute :magic_encoding
          execute :kill,"-QUIT","`cat #{deploy_to}/current/tmp/pids/guike_unicorn.pid`"
          sleep(5)
          execute :unicorn_rails,"-c","#{deploy_to}/current/config/unicorn.rb","--env","production","-D"
        end
      end
    end
  end

  desc "rake assets"
  task :compile_assets do
    on roles(:app) do
      within "#{fetch(:deploy_to)}/current" do
         with RAILS_ENV: fetch(:rails_env) do
           execute :rake,"assets:precompile","RAILS_ENV=production"
         end 
      end  
    end  
  end 

   desc "create DB"
  task :create_db do
    on roles(:app) do
      within "#{release_path}" do
         with RAILS_ENV: fetch(:rails_env) do
           execute :rake,"db:create"
         end 
      end  
    end  
  end 

   # before :migrate, :create_db
   after :published, :compile_assets
   after :published, :restart_unicorn


end


